package com.qf.controller;
/**
 * @author ZERO
 * @date 2021/12/24 10:51
 */

import com.qf.pojo.Movie;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 *@program: com.qf.controller
 *@description: movie控制
 *@author: ZERO
 *@create: 2021/12/24 10:51
 */
@RestController
@RequestMapping("movie")
public class MovieController {
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @RequestMapping("findMovies")
    public List<Movie> findMovies(){
        //获取查询工厂对象
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //获取查询对象
        NativeSearchQuery nativeSearchQuery =
                nativeSearchQueryBuilder.withQuery(
                        //具体的查询类型对象，匹配方式
                        new RangeQueryBuilder("year")//根据范围查询
                        .from("2012",true)//包含2012
                        .to("2016",false)//不包含2016
                ).build();
        //获取hits对象
        SearchHits<Movie> searchHits = elasticsearchRestTemplate.search(
                nativeSearchQuery,Movie.class, IndexCoordinates.of("movies"));
        //获取命中的数据
        List<SearchHit<Movie>> searchHitList = searchHits.getSearchHits();
        //遍历并存入创建的集合中
        List<Movie> movieList = new ArrayList<>();
        for (SearchHit<Movie> movieSearchHit :searchHitList){
            movieList.add(movieSearchHit.getContent());
        }
        return movieList;
    }
}
